//
//  YCMyIdentityViewController.m
//  YCSchool
//
//  Created by gmall on 16/5/9.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  我的身份

#import "YCMyIdentityViewController.h"
#import "FBKVOController.h"
#import "YCWebViewController.h"
#import "YCUpdateNameViewController.h"
#import "YCUpdatePhoneViewController.h"

#import "YCPickerContainerView.h"

#import "YCMeInfoModel.h"
#import "YCBirthdayModel.h"

NSString * const YCAccountDataTitle         =  @"t";
NSString * const YCAccountDataValue         =  @"v";
NSString * const YCAccountDataHeight        = @"h";
NSString * const YCAccountDataAction        = @"a";
NSString * const YCAccountDataAccessoryNone = @"ac";
NSString * const YCAccountDataValueChange = @"GMAccountDataValueChange";


@interface YCMyIdentityViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,YCPickerContainerViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic,readonly) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *sections;
@property (nonatomic,readonly) UIView *footerView;
@property (nonatomic,readonly) UIImageView *avatorImageView;
@property (nonatomic,readonly) UIDatePicker *datePicker;
@property (nonatomic,readonly) YCPickerContainerView *pickerContainerView;
@property (nonatomic,readonly) UIPickerView *addressPickerView;
@property (nonatomic,readonly) NSArray *citys;
@property (nonatomic,readonly) UIImageView *validateImageView;
@property (nonatomic,readonly) NSString *constellationStr;


@end

@implementation YCMyIdentityViewController

@synthesize tableView = _tableView;
@synthesize sections = _sections;
@synthesize footerView = _footerView;
@synthesize avatorImageView = _avatorImageView;
@synthesize validateImageView = _validateImageView;
@synthesize datePicker = _datePicker;
@synthesize pickerContainerView = _pickerContainerView;
@synthesize citys = _citys;
@synthesize addressPickerView = _addressPickerView;



#pragma mark - 属性获取方法

- (UITableView *)tableView
{
    if(!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

- (UIView *)footerView
{
    if(!_footerView)
    {
        CGFloat width = self.view.bounds.size.width;
        
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 81)];
        
        UIButton *button = [[UIButton alloc] init];
        button.backgroundColor = [UIColor blackColor];
        button.layer.cornerRadius = 35 / 2;
        button.layer.masksToBounds = YES;
        [button setTitle:@"退出登录" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button addTarget:self action:@selector(didTouchUpInsideLogOutButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [_footerView addSubview:button];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_footerView);
            make.left.equalTo(_footerView).offset(50);
            make.right.equalTo(_footerView).offset(-50);
            make.height.equalTo(@35);
        }];
    }
    return _footerView;
}

- (UIImageView *)avatorImageView
{
    if(!_avatorImageView)
    {
        _avatorImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 60)/2.0, 26, 60, 60)];
        _avatorImageView.layer.cornerRadius = 60 / 2.0;
        _avatorImageView.contentMode = UIViewContentModeScaleAspectFill;
        _avatorImageView.layer.masksToBounds = YES;
        _avatorImageView.tag = 10000;
    }
    return _avatorImageView;
}

- (UIDatePicker *)datePicker
{
    if(!_datePicker)
    {
        _datePicker = [[UIDatePicker alloc] init];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        _datePicker.maximumDate = [NSDate date];
        _datePicker.minimumDate = [@"1900-01-01" yc_dateWithDateFormatString:@"yyyy-MM-dd"];
        _datePicker.date = [@"1990-01-01" yc_dateWithDateFormatString:@"yyyy-MM-dd"];
        _datePicker.backgroundColor = [UIColor whiteColor];
    }
    return _datePicker;
}

- (NSArray *)citys
{
    if(!_citys)
    {
        _citys = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"address" ofType:@"plist"]];
    }
    return _citys;
}

- (YCPickerContainerView *)pickerContainerView
{
    if(!_pickerContainerView)
    {
        _pickerContainerView = [[YCPickerContainerView alloc] init];
        _pickerContainerView.delegate = self;
    }
    return _pickerContainerView;
}

- (UIPickerView *)addressPickerView
{
    if(!_addressPickerView)
    {
        _addressPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 200)];
        _addressPickerView.dataSource = self;
        _addressPickerView.delegate = self;
        _addressPickerView.backgroundColor = [UIColor whiteColor];
    }
    return _addressPickerView;
}

- (NSMutableArray *)sections
{
    if(!_sections)
    {
//        GOLoginUser *loginUser = [GOLoginUser loginUser];
        NSDate *date = [@"2016/5/9" yc_dateWithDateFormatString:@"dd/MM/yyyy"];
        int mouth = [[date yc_dateStringWithFormatString:@"MM"] intValue];
        int day = [[date yc_dateStringWithFormatString:@"dd"] intValue];
        
        NSString *astroString = [NSString yc_getAstroWithMonth:mouth day:day];
        _sections = [[NSMutableArray alloc] init];
        NSMutableArray *rows;
        
        rows = [[NSMutableArray alloc] init];
        [rows addObject:[@{YCAccountDataTitle:@"头像",
                           YCAccountDataValue:@"",
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedUserAvatorIndexPath:))} mutableCopy]];
        [_sections addObject:rows];
        
        rows = [[NSMutableArray alloc] init];
        [rows addObject:[@{YCAccountDataTitle:@"姓名",
                           YCAccountDataValue:@"张行",
                           YCAccountDataValueChange:@(NO),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedNameIndexPath:))} mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"性别",
                           YCAccountDataValue:@"男",
                           YCAccountDataAccessoryNone:@(NO),
                           YCAccountDataValueChange:@(NO),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedGenderIndexPath:))} mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"出生年月",
                           YCAccountDataValue:@"1990-01-01",
                           YCAccountDataAccessoryNone:@(NO),
                           YCAccountDataValueChange:@(NO),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedBirthIndexPath:))
                           } mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"星座",
                           YCAccountDataValue:_constellationStr ? _constellationStr : @"",
                           YCAccountDataAccessoryNone:@(YES),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedXZIndexPath:))
                           } mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"婚姻状态",
                           YCAccountDataValue:@"否",
                           YCAccountDataValueChange:@(NO),
                           YCAccountDataAccessoryNone:@(NO),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedStatusIndexPath:))} mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"常驻城市",
                           YCAccountDataValue:@"未设置",
                           YCAccountDataValueChange:@(NO),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedCityIndexPath:))} mutableCopy]];
        
        [_sections addObject:rows];
        
        rows = [[NSMutableArray alloc] init];
        [rows addObject:[@{YCAccountDataTitle:@"手机号码",
                           YCAccountDataValue:@"12345678912",
                           YCAccountDataAccessoryNone:@(NO),
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedPhoneIndexPath:))} mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"密码设定",
                           YCAccountDataValue:@"",
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedPasswordIndexPath:))} mutableCopy]];
        [_sections addObject:rows];
        
        rows = [[NSMutableArray alloc] init];
        [rows addObject:[@{YCAccountDataTitle:@"收货地址信息",
                           YCAccountDataValue:@"",
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedReceivingAddressIndexPath:))} mutableCopy]];
        [_sections addObject:rows];
        
//        if([GOLoginUser loginUser].userType == GOLoginUserTypeNormal)
//        {
//            rows = [[NSMutableArray alloc] init];
//            [rows addObject:[@{YCAccountDataTitle:@"申请商家帐号",
//                               YCAccountDataValue:@"",
//                               YCAccountDataAction:NSStringFromSelector(@selector(selectedSQKTDPIndexPath:))} mutableCopy]];
//            [_sections addObject:rows];
//        }
        
        rows = [[NSMutableArray alloc] init];
        //        [rows addObject:[@{GOAccountDataTitle:@"关于我们",
        //                           GOAccountDataValue:@"",
        //                           GOAccountDataAction:NSStringFromSelector(@selector(selectedAboutUsIndexPath:))} mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"用户协议",
                           YCAccountDataValue:@"",
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedUserProtocolIndexPath:))} mutableCopy]];
        
        
        NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        NSInteger v = [[[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey] integerValue];
        
        NSString *v1 = [NSString stringWithFormat:@"V%@.%lu",version,(long)v];
        
        [rows addObject:[@{YCAccountDataTitle:@"版本更新",
                           YCAccountDataValue:v1,
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedUpdateIndexPath:))} mutableCopy]];
        
        [rows addObject:[@{YCAccountDataTitle:@"反馈",
                           YCAccountDataValue:@"",
                           YCAccountDataAction:NSStringFromSelector(@selector(selectedFeedBackIndexPath:))} mutableCopy]];
        [_sections addObject:rows];
        
        //        rows = [[NSMutableArray alloc] init];
        //        [rows addObject:[@{GOAccountDataTitle:@"设置",
        //                           GOAccountDataValue:@"",
        //                           GOAccountDataAction:NSStringFromSelector(@selector(selectedSettingIndexPath:))} mutableCopy]];
        //        [_sections addObject:rows];
    }
    return _sections;
}


#pragma mark - 视图控制器生命周期

- (void)dealloc
{
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userNickName"];
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userSex"];
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userHeadPhoto"];
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userMobilePhone"];
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userBirthdayStr"];
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userMarriageStatus"];
//    [self.KVOController unobserve:[GOLoginUser loginUser] keyPath:@"userPlaceStr"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.title = NSLocalizedString(@"我的身份", nil);
    [self yc_addBackBarButtonItem];
    
    @yc_weakify(self);
    
    FBKVONotificationBlock block = ^(id observer, id object, NSDictionary *change) {
        @yc_strongify(self);
        if(!self) return;
        
        self.sections = nil;
        [self.tableView reloadData];
    };
    
//    GOLoginUser *loginUser = [GOLoginUser loginUser];
    
//    [self.KVOController observe:loginUser keyPath:@"userNickName" options:NSKeyValueObservingOptionNew block:block];
//    [self.KVOController observe:loginUser keyPath:@"userSex" options:NSKeyValueObservingOptionNew block:block];
//    [self.KVOController observe:loginUser keyPath:@"userHeadPhoto" options:NSKeyValueObservingOptionNew block:block];
//    [self.KVOController observe:loginUser keyPath:@"userMobilePhone" options:NSKeyValueObservingOptionNew block:block];
//    [self.KVOController observe:loginUser keyPath:@"userBirthdayStr" options:NSKeyValueObservingOptionNew block:block];
//    [self.KVOController observe:loginUser keyPath:@"userMarriageStatus" options:NSKeyValueObservingOptionNew block:block];
//    [self.KVOController observe:loginUser keyPath:@"userPlaceStr" options:NSKeyValueObservingOptionNew block:block];
    
    [self layout];
    [self loadData];
}

#pragma mark - 自定义的方法

- (void)layout
{
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = self.footerView;
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.and.left.right.equalTo(self.view);
    }];
}

#pragma mark - 数据处理

+ (void)load
{
    [YCMeInfoModel yc_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"username":@"uname",
                 @"birthdayModel":@"birthext"
                 };
    }];
    
    [YCBirthdayModel yc_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"birthday":@"birth"
                 };
    }];
}

- (void)loadData
{


    // 测试我的身份接口
    NSDictionary *params = @{@"uid":@(1),
                             @"token":@"6840c3286f6e6393169943fdbb2bf213"};
    [[YCNetworManager shareManager] postWithUrl:YCAPIUserInfoself params:params success:^(NSURLSessionDataTask *task, ServiceResponse *response) {
        YCMeInfoModel *model = [YCMeInfoModel yc_objectWithKeyValues:response.data];
        YCLog(@"转换后的模型：%@",model);
        YCLog(@"%@",response.data);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        YCLog(@"%@",error.localizedDescription);
    }];
}

#pragma mark - 点击行响应方法

///退出登录
- (void)didTouchUpInsideLogOutButton:(UIButton *)button
{
//    GOSystemAlertView *alertView = [[GOSystemAlertView alloc] initWithTitle:@"提示"
//                                                                    message:@"退出后不会删除任何历史数据，下次登录依然可以使用本帐号"
//                                                                   delegate:nil
//                                                          cancelButtonTitle:@"取消"
//                                                          otherButtonTitles:@"退出",nil];
//    [alertView showUsingClickButtonBlock:^(UIAlertView *alertView, NSUInteger atIndex) {
//        if(alertView.cancelButtonIndex != atIndex)
//        {
//            [[GOAppDelegate shared] logout];
//        }
//    }];
}

/**
 *  选择版本更新
 *
 *  @param path 行路径
 */
- (void)selectedUpdateIndexPath:(NSIndexPath *)path
{
#ifdef MYAPPDELEGATE
    ///测试
    NSString * url = @"http://202.104.110.176:8088/usersoft/softnews/down.html";
#elif DEBUG
    ///开发
    NSString * url = @"http://202.104.110.176:8088/usersoft/softnews/down.html";
#else
    ///正式
    NSString * url = @"http://202.104.110.176:8088/usersoft/softnews/down.html";
#endif
    
    if(url)
    {
        YCWebViewController *vc = [[YCWebViewController alloc] initWithURLString:url];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
//        GOSystemAlertView *alertView = [[GOSystemAlertView alloc] initWithTitle:@"提示"
//                                                                        message:@"当前版本为开发版，如需更新请找程序"
//                                                                       delegate:nil
//                                                              cancelButtonTitle:@"确定"
//                                                              otherButtonTitles:nil];
//        [alertView showUsingClickButtonBlock:^(UIAlertView *alertView, NSUInteger atIndex) {
//            
//        }];
    }
    
}


/**
 *  选择头像行
 *
 *  @param path 行路径
 */
- (void)selectedUserAvatorIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
    
    LXActionSheet *sheet = [[LXActionSheet alloc] initWithCancelButtonTitle:@"取消"
                                              otherButtonTitlesArray:@[@"拍照",@"从手机相册选择"]];
    
    [sheet showInView:self.view mask:YES click:^(NSUInteger index, LXActionSheet *sheet) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = index == 2 ? UIImagePickerControllerSourceTypePhotoLibrary : UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    } cancel:^(NSUInteger index, LXActionSheet *sheet) {
        
    }];
    
    
}

/**
 *  选择姓名行
 *
 *  @param path 行路径
 */
- (void)selectedNameIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
    
    YCUpdateNameViewController *vc = [[YCUpdateNameViewController alloc] initWithName:@"张行"];
    vc.title = @"修改姓名";
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:^{
        
    }];
}
/**
 *  选择性别行
 *
 *  @param path 行路径
 */
- (void)selectedGenderIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
    
    LXActionSheet *sheet = [[LXActionSheet alloc] initWithCancelButtonTitle:@"取消" otherButtonTitlesArray:@[@"女",@"男"]];
    [sheet showInView:self.navigationController.view mask:YES click:^(NSUInteger index, LXActionSheet *sheet) {
        
        NSInteger v = index == 2 ? 1 : 2;
//        if([GOLoginUser loginUser].userSex != v)
//        {
//            NSDictionary *ps = @{@"sex":@(v)};
//            
//            @go_weakify(self);
//            
//            GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                
//                @go_strongify(self);
//                if(!self) return;
//                
//                if(response.success)
//                {
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        [SVProgressHUD dismiss];
//                        
//                    });
//                    
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        GOLoginUser *loginUser = [GOLoginUser loginUser];
//                        loginUser.userSex = v;
//                        [GOLoginUser loginWithUser:loginUser];
//                    });
//                }
//                else
//                {
//                    
//                }
//            };
//            
//            GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//                
//            };
//            
//            [SVProgressHUD showWithStatus:@"提交中..."];
//            
//            [[GOWebService service] postAction:GOAPIUserInfoUpdate
//                                        params:ps
//                                       success:success
//                                       failure:failure];
//        }
//        
    } cancel:^(NSUInteger index, LXActionSheet *sheet)
     {
         
     }];
}
/**
 *  选择出生年月行
 *
 *  @param path 行路径
 */
//- (void)selectedBirthIndexPath:(NSIndexPath *)path
//{
//    NSDate *date = [@"1990-01-01" yc_dateWithDateFormatString:@"yyyy-MM-dd"];
//    if(date)
//    {
//        self.datePicker.date = date;
//    }
//    
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    self.pickerContainerView.title = NSLocalizedString(@"选择生日", nil);
//    [self.pickerContainerView showDatePicker:self.datePicker inView:self.navigationController.view];
//}
/**
 *  选择星座
 *
 *  @param path 行路径
 */
//- (void)selectedXZIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//}

/**
 *  选择婚恋状态   1单身 2已婚 5恋爱中 空表示不修改
 *
 *  @param path 行路径
 */
//- (void)selectedStatusIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    GOActionSheet *sheet = [[GOActionSheet alloc] initWithTitle:nil message:nil cancelButtonTitle:@"取消" otherButtonTitles:@"已婚",@"单身",nil];
//    [sheet showInView:self.navigationController.view mask:YES click:^(NSUInteger index, GOActionSheet *sheet) {
//        
//        NSInteger v = index == 2 ? 1 : 3;
//        if([GOLoginUser loginUser].userMarriageStatus != v)
//        {
//            NSDictionary *ps = @{@"marriageStatus":@(v)};
//            
//            @go_weakify(self);
//            
//            GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                
//                @go_strongify(self);
//                if(!self) return;
//                
//                if(response.success)
//                {
//                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                        [SVProgressHUD dismiss];
//                        
//                    });
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        GOLoginUser *loginUser = [GOLoginUser loginUser];
//                        loginUser.userMarriageStatus = v;
//                        [GOLoginUser loginWithUser:loginUser];
//                    });
//                }
//                else
//                {
//                    
//                }
//            };
//            
//            GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//                
//            };
//            
//            [SVProgressHUD showWithStatus:@"提交中..."];
//            
//            [[GOWebService service] postAction:GOAPIUserInfoUpdate
//                                        params:ps
//                                       success:success
//                                       failure:failure];
//        }
//        
//    } cancel:^(NSUInteger index, GOActionSheet *sheet)
//     {
//         
//     }];
//    
//}

/**
 *  选择常居城市
 *
 *  @param path 行路径x
 */
//- (void)selectedCityIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    NSString *province = [GOLoginUser loginUser].userProvince;
//    NSString *city = [GOLoginUser loginUser].userCity;
//    
//    if([city hasSuffix:@"市"])
//    {
//        city = [city substringToIndex:city.length - 1];
//    }
//    
//    NSUInteger pIndex = [self.citys indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
//        return [obj[@"name"] isEqualToString:province];
//    }];
//    
//    if(pIndex < self.citys.count)
//    {
//        NSArray *citys = self.citys[pIndex][@"city"];
//        
//        NSUInteger cIndex = [citys indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
//            return [obj[@"name"] isEqualToString:city];
//        }];
//        
//        if(cIndex < citys.count)
//        {
//            [self.addressPickerView selectRow:pIndex inComponent:0 animated:NO];
//            [self.addressPickerView selectRow:cIndex inComponent:1 animated:NO];
//        }
//    }
//    
//    
//    self.pickerContainerView.title = NSLocalizedString(@"选择地区", nil);
//    
//    [self.pickerContainerView showPickerView:self.addressPickerView inView:self.navigationController.view];
//}

/**
 *  选择手机号码行
 *
 *  @param path 行路径
 */
//- (void)selectedPhoneIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    YCUpdatePhoneViewController *vc = [[YCUpdatePhoneViewController alloc] initWithPhone:@"12345678912";
//    vc.title = @"修改手机号码";
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
//    [self presentViewController:nav animated:YES completion:^{
//        
//    }];
//}

/**
 *  选择密码设置行
 *
 *  @param path 行路径
 */
//- (void)selectedPasswordIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    YCEditorPasswordViewController *vc = [[YCEditorPasswordViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
//}

/**
 *  收货地址信息维护
 *
 *  @param path 行路径
 */
//- (void)selectedReceivingAddressIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    YCAddressManageViewController *vc = [[YCAddressManageViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
//}

/**
 *  申请开通店铺
 *
 *  @param path 行路径
 */
//- (void)selectedSQKTDPIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    YCApplyMerchantAccountViewController *vc = [[YCApplyMerchantAccountViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
//    self.navigationController.go_markViewController = vc;
//}

/**
 *  选择关于我们行
 *
 *  @param path 行路径
 */
- (void)selectedAboutUsIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
}

/**
 *  选择用户协议
 *
 *  @param path 行路径
 */
//- (void)selectedUserProtocolIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    GOWebViewController *usVC = [[GOWebViewController alloc] initWithURLString:@"http://ios.legacy.hk:8899/myapp/xieyi.html"];
//    [self.navigationController pushViewController:usVC animated:YES];
//}

/**
 *  反馈
 *
 *  @param path 行路径
 */
//- (void)selectedFeedBackIndexPath:(NSIndexPath *)path
//{
//    [self.tableView deselectRowAtIndexPath:path animated:YES];
//    
//    GOFeedbackViewController *vc = [[GOFeedbackViewController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
//}

/**
 *  选择设置行
 *
 *  @param path 行路径
 */
- (void)selectedSettingIndexPath:(NSIndexPath *)path
{
    [self.tableView deselectRowAtIndexPath:path animated:YES];
}

#pragma mark - UITableView delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *rows = self.sections[section];
    return rows.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0 || section == 1) return 13;
    return 6.5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if(section == 0) return 13;
    if(section == (self.sections.count - 1)) return 2.0;
    return 6.5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *rowData = self.sections[indexPath.section][indexPath.row];
    if([rowData[YCAccountDataTitle] isEqualToString:@"头像"])
    {
        return 112;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CELLID = @"CELLID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELLID];
    NSMutableDictionary *rowData = self.sections[indexPath.section][indexPath.row];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CELLID];
        cell.detailTextLabel.textColor = [UIColor blackColor];
        cell.textLabel.textColor = [UIColor yc_colorWithUInt:0x757575];
        cell.textLabel.font = [UIFont systemFontOfSize:16];
        cell.detailTextLabel.font = cell.textLabel.font;
    }
    
    cell.accessoryType = [rowData[YCAccountDataAccessoryNone] boolValue] ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = rowData[YCAccountDataTitle];
    cell.detailTextLabel.text = rowData[YCAccountDataValue];
    
    if([rowData[YCAccountDataTitle] isEqualToString:@"头像"])
    {
        [self.avatorImageView yc_setWebImageWithURLString:@"" holderSize:CGSizeMake(60, 60)];
        [cell.contentView addSubview:self.avatorImageView];
        
    }
    else
    {
        [[cell.contentView viewWithTag:10000] removeFromSuperview];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSMutableDictionary *rowData = self.sections[indexPath.section][indexPath.row];
    NSString *actionString = rowData[YCAccountDataAction];
    if(actionString)
    {
        SEL action = NSSelectorFromString(actionString);
        if([self respondsToSelector:action])
        {
            void (* gm_objc_msgSend)(id,SEL,id) = (void (*)(id,SEL,id))objc_msgSend;
            gm_objc_msgSend(self,action,indexPath);
        }
    }
}

#pragma mark -- UIImagePickerController delegate

//    添加图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    if(!img)
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    if(img.imageOrientation != UIImageOrientationUp)
    {
        UIGraphicsBeginImageContext(img.size);
        [img drawAtPoint:CGPointZero];
        img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    
//    GOCropPhotoViewCompletion completion = ^(GOCropPhotoViewController *vc,UIImage *image){
//        
//        GOUploadFile *file = [GOUploadFile uploadFileWihType:GOUploadFileTypeImage
//                                                        data:UIImageJPEGRepresentation(image,0.65)
//                                                         key:@"headPhoto"];
//        
//        [SVProgressHUD showWithStatus:@"正在上传..."];
//        
//        @go_weakify(self);
//        
//        [[GOWebService service] postAction:GOAPIUserInfoUpdate
//                                    params:nil
//                                      file:file
//                                   success:^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                                       
//                                       @go_strongify(self);
//                                       if(!self) return;
//                                       
//                                       if(response.success)
//                                       {
//                                           
//                                           SDWebImageManager *manager = [SDWebImageManager sharedManager];
//                                           [manager saveImageToCache:image forURL:[NSURL URLWithString:file.remotePath]];
//                                           
//                                           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                                               [SVProgressHUD dismiss];
//                                           });
//                                           
//                                           dispatch_async(dispatch_get_main_queue(), ^{
//                                               
//                                               GOLoginUser *user = [GOLoginUser loginUser];
//                                               user.userHeadPhoto = file.remotePath;
//                                               [GOLoginUser loginWithUser:user];
//                                               
//                                               [self.tableView reloadData];
//                                           });
//                                       }
//                                       else
//                                       {
//                                           
//                                       }
//                                   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                                       
//                                   }];
//        
//    };
//    
//    GOCropPhotoViewController *c = [[GOCropPhotoViewController alloc] initWithImage:img
//                                                                         completion:completion];
//    [picker pushViewController:c animated:YES];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - UIPickerView delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component == 0) return self.citys.count;
    return [self.citys[[pickerView selectedRowInComponent:0]][@"city"] count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title;
    
    if(component == 0)
    {
        title = self.citys[row][@"name"];
    }
    else
    {
        NSArray *citys = self.citys[[pickerView selectedRowInComponent:0]][@"city"];
        if(row < citys.count)
        {
            title = citys[row][@"name"];
        }
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(component == 0)
    {
        [pickerView reloadComponent:1];
        [pickerView selectRow:0 inComponent:1 animated:YES];
    }
    else
    {
        NSArray *citys = self.citys[[pickerView selectedRowInComponent:0]][@"city"];
        if(row >= citys.count)
        {
            [pickerView selectRow:citys.count - 1 inComponent:1 animated:NO];
        }
    }
}

- (void)pickerContainerViewDidDone:(YCPickerContainerView *)containerView
{
    if (containerView.pickerView == self.datePicker)
    {
        NSDate *date = self.datePicker.date;
        NSString *dateString = [date yc_dateStringWithFormatString:@"dd/MM/yyyy"];
        
        NSDictionary *ps = @{@"birthday":@([date timeIntervalSince1970]*1000)};
        
        @yc_weakify(self);
        
//        GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//            
//            @go_strongify(self);
//            if(!self) return;
//            
//            if(response.success)
//            {
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [SVProgressHUD dismiss];
//                });
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    GOLoginUser *loginUser = [GOLoginUser loginUser];
//                    loginUser.userBirthdayStr = dateString;
//                    [GOLoginUser loginWithUser:loginUser];
//                    
//                });
//            }
//            else
//            {
//                
//            }
//        };
//        
//        GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        };
//        
//        [SVProgressHUD showWithStatus:@"提交中..."];
//        [[GOWebService service] postAction:GOAPIUserInfoUpdate
//                                    params:ps
//                                   success:success
//                                   failure:failure];
//    }
//    else if (containerView.pickerView == self.addressPickerView)
//    {
//        NSUInteger pIndex = [self.addressPickerView selectedRowInComponent:0];
//        NSUInteger cIndex = [self.addressPickerView selectedRowInComponent:1];
//        
//        NSDictionary *provinceDict = self.citys[pIndex];
//        NSString *pro = provinceDict[@"name"];
//        NSString *city = provinceDict[@"city"][cIndex][@"name"];
//        
//        GOLoginUser *user = [GOLoginUser loginUser];
//        if(pro == user.userProvince && city ==  user.userCity)
//        {
//            return;
//        }
//        NSDictionary *ps = @{@"province":pro,
//                             @"city":city};
//        
//        @go_weakify(self);
//        
//        GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//            
//            @go_strongify(self);
//            if(!self) return;
//            
//            if(response.success)
//            {
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.65 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [SVProgressHUD dismiss];
//                });
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    GOLoginUser *loginUser = [GOLoginUser loginUser];
//                    loginUser.userPlaceStr = [NSString stringWithFormat:@"%@ %@",pro,city];
//                    loginUser.userCity = city;
//                    loginUser.userProvince = pro;
//                    [GOLoginUser loginWithUser:loginUser];
//                });
//            }
//            else
//            {
//                
//            }
//        };
//        
//        GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//            
//        };
//        
//        [SVProgressHUD showWithStatus:@"提交中..."];
//        
//        [[GOWebService service] postAction:GOAPIUserInfoUpdate
//                                    params:ps
//                                   success:success
//                                   failure:failure];
    }
}

///星座判断
- (NSString *)getAstroWithMonth:(int)m day:(int)d{
    
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    if (m<1||m>12||d<1||d>31){
        return @"错误日期格式!";
    }
    if(m==2 && d>29)
    {
        return @"错误日期格式!!";
    }else if(m==4 || m==6 || m==9 || m==11) {
        if (d>30) {
            return @"错误日期格式!!!";
        }
    }
    result=[NSString stringWithFormat:@"%@",[astroString substringWithRange:NSMakeRange(m*2-(d < [[astroFormat substringWithRange:NSMakeRange((m-1), 1)] intValue] - (-19))*2,2)]];
    
    _constellationStr = [NSString stringWithFormat:@"%@座",result];
    
    return result;
}
     
@end

